package com.encrypt.encrptspringbootstarter.configer;

import com.encrypt.encrptspringbootstarter.interceptor.ParameterInterceptor;
import com.encrypt.encrptspringbootstarter.interceptor.ResultSetInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

@Configuration
public class MyBatisConfig {

    @Value("${spring.datasource.url}")
    private String dbUrl;

    @Value("${spring.datasource.username}")
    private String dbUsername;

    @Value("${spring.datasource.password}")
    private String dbPassword;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl(dbUrl);
        dataSource.setUsername(dbUsername);
        dataSource.setPassword(dbPassword);
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        return factoryBean;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(SqlSessionFactoryBean factoryBean) throws Exception {
        factoryBean.setPlugins(new Interceptor[]{new ParameterInterceptor(),new ResultSetInterceptor()});
        SqlSessionFactory object = factoryBean.getObject();
        object.getConfiguration().addInterceptor(new ParameterInterceptor());
        object.getConfiguration().addInterceptor(new ResultSetInterceptor());
        return factoryBean.getObject();
    }
}